

function $_AjaxQueue($capacity){
	this.totalRequests = 0;
	this.capacity = $capacity;

	this.queue = [];
	this.queueTotal = 0;
	
	this.busy = {};
	this.busyTotal = 0;
}

// wrapper for request method
$_AjaxQueue.prototype.add = function($id, $function){
	if(this.busyTotal<this.capacity){
		this.makeBusy($id, $function);
	}else{
		this.makeWait($id, $function);
	}
}


$_AjaxQueue.prototype.makeBusy = function($id, $function){
		this.busyTotal++;
		this.busy[$id] = { 
			id:$id,
			func:$function
		};
		this.busy[$id].func();
		//window.defaultStatus += "b"+ $id;
}


$_AjaxQueue.prototype.makeWait = function($id, $function){
		this.queue.push({
			id:$id,
			func:$function
		});
		this.queueTotal++;
		//window.defaultStatus += "q"+ $id;
}



// add as last line in callback
$_AjaxQueue.prototype.complete = function($id){
	delete this.busy[$id];
//	alert(this.busyTotal);
	if(this.busyTotal>0){
	this.busyTotal--;	
	if(this.queueTotal!=0){
		this.next();
	 }
	}

}


// Makes the next one in que busy
$_AjaxQueue.prototype.next = function(){
	var _item = this.queue.shift();
	this.makeBusy(_item.id, _item.func);
	this.queueTotal--;
}